package com.scorpio.framework.service;

import com.scorpio.common.utils.file.FileUploadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.util.UUID;

@Service
public class MailService {
    private static final Logger log = LoggerFactory.getLogger(MailService.class);

    @Value("${spring.mail.username}")
    private String username;

    @Value("${contract.jiePath}")
    private String jiePath;

    @Autowired
    private JavaMailSender mailSender;

    //发邮件
    public boolean sendMail(String title, MultipartFile file, String... toMail) {
        if (toMail == null || toMail.length <= 0) return false;
        String extension = FileUploadUtils.getExtension(file);
        File f = new File(jiePath + "/" + UUID.randomUUID().toString().replaceAll("-", "") + "." + extension);
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            //创建邮件内容
            helper.setFrom(username);//这里指的是发送者的账号
            helper.setTo(toMail);
            helper.setSubject(title);
            helper.setText("");
            file.transferTo(f);
            FileSystemResource resource = new FileSystemResource(f);
            helper.addAttachment(MimeUtility.encodeWord("附件1." + extension), resource);
            mailSender.send(message);
        } catch (Exception e) {
            log.error("邮件发送失败", e);
            return false;
        } finally {
            if (f.exists()) {
                f.delete();
            }
        }
        return true;
    }


}
